package com.ruoyi.js.utils;

import com.ruoyi.js.domain.JsRegisterScore;
import com.ruoyi.js.domain.JsScore;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ScoreUtils {


    // 大于三个裁判去最高最低求平均分，小于等于三个直接平均分
    public static Double computeRegisterScore(List<JsScore> scoreList){
        if(scoreList.size() == 0){
            return  null;
        }
        Map<Long, Double> judgeScoreMap = scoreList.stream().collect(Collectors.groupingBy(JsScore::getJudgeId, Collectors.summingDouble(JsScore::getValue)));
        DoubleSummaryStatistics summaryStatistics = judgeScoreMap.values().stream().collect(Collectors.summarizingDouble(Double::doubleValue));
        double score = summaryStatistics.getAverage();
        long count = summaryStatistics.getCount();
        if(count > 3){
            double sum = summaryStatistics.getSum();
            double max = summaryStatistics.getMax();
            double min = summaryStatistics.getMin();
             score = (sum - min - max) / (count - 2);
        }
        return score;
    }


    public static Double roundDoubleValue(Double value, int scale){
        return new BigDecimal(String.valueOf(value)).setScale(scale, RoundingMode.HALF_UP).doubleValue();
    }

    public static String roundDoubleValueStr(Double value, int scale){
        if(value == null){
            return "";
        }else {
            return new BigDecimal(String.valueOf(value)).setScale(scale, RoundingMode.HALF_UP).toString();
        }
    }

    public static void computeScoreRanking(List<JsRegisterScore> registerScoreList){
        registerScoreList.forEach(r -> r.setFinalScore(roundDoubleValue(r.getFinalScore(), 2)));
        List<Map.Entry<Double, List<JsRegisterScore>>> list = registerScoreList.stream().collect(Collectors.groupingBy(JsRegisterScore::getFinalScore)).entrySet()
                .stream().sorted((s1, s2) -> -Double.compare(s1.getKey(), s2.getKey())).collect(Collectors.toList());
        int index = 1;
        for (Map.Entry<Double, List<JsRegisterScore>> entry : list) {
            for(JsRegisterScore result : entry.getValue()){
                result.setRanking(index);
            }
            index += entry.getValue().size();
        }
        registerScoreList.sort(Comparator.comparing(JsRegisterScore::getRanking));
    }

}
